﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ServiceStack.Redis;

namespace Common
{
    public class RedisHelper
    {
        /// <summary>
        /// ip
        /// </summary>
        private const string host = "127.0.0.1";
        /// <summary>
        /// 端口号
        /// </summary>
        private const int port = 6379;


        private RedisClient _redisClient = null;
        public RedisClient redisClient
        {

            get
            {

                if (_redisClient == null)
                {
                    _redisClient = new RedisClient(host, port);
                }
                return _redisClient;
            }
        }




        /// <summary>
        /// redis存值 缓存单个数据对象
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="dt">设置缓存数据的时间</param>
        /// <returns></returns>
        public bool SetValue<T>(string key, T value, DateTime dt)
        {

            try
            {
                return redisClient.Set<T>(key, value, dt);

            }
            catch (Exception ex)
            {
                return false;
            }

        }
        /// <summary>
        /// 缓存集合
        /// </summary> 
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="value"></param>
        /// <param name="dt"></param>
        /// <returns></returns>
        public bool SetValue<T>(string key, List<T> value, DateTime dt)
        {

            try
            {
                return redisClient.Set<List<T>>(key, value);

            }
            catch (Exception ex)
            {
                return false;
            }

        }

        /// <summary>
        /// redis获取值
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T GetValue<T>(string key)
        {
            try
            {

                return redisClient.Get<T>(key);
            }
            catch (Exception ex)
            {

                throw;
            }
        }


        /// <summary>
        /// 删除
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="entyty"></param>
        public void DeletKey<T>(T entity) where T : class,new()
        {

            try
            {
                //制定删除某一个数据对象
                redisClient.Delete<T>(entity);
                //删除缓存里面所有的数据
                //redisClient.DeleteAll<T>();
            }
            catch (Exception)
            {

                throw;
            }

        }

    }
}
